import React, { useState, useEffect } from 'react'
import { useAtom } from 'jotai'
import { Capacitor } from '@capacitor/core'
import { textAssistantAtom, clipboardAtom } from '../stores/textAssistantAtoms'
import { presetCategories } from '../stores/presetTemplates'
import { AndroidPermissions } from '../mobile/AndroidPermissions'
import './AssistantPanel.scss'

interface AssistantPanelProps {
  onClose: () => void
}

export const AssistantPanel: React.FC<AssistantPanelProps> = ({ onClose }) => {
  const [state, setState] = useAtom(textAssistantAtom)
  const [clipboardText, setClipboardText] = useAtom(clipboardAtom)
  const [inputText, setInputText] = useState('')
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null)
  const isMobile = Capacitor.isNativePlatform()

  useEffect(() => {
    if (!state.isVisible) return
    // If there is pending input from overlay in atom, use it; otherwise try clipboard
    if (state.currentInput && state.currentInput.trim().length > 0) {
      setInputText(state.currentInput)
    } else {
      loadClipboardContent()
    }
  }, [state.isVisible])

  // Keep local textarea in sync with atom's currentInput updates
  useEffect(() => {
    if (state.isVisible && state.currentInput !== inputText) {
      setInputText(state.currentInput || '')
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state.currentInput])

  const loadClipboardContent = async () => {
    try {
      if (isMobile) {
        const hasPermission = await AndroidPermissions.checkClipboardPermission()
        if (!hasPermission) return
      }

      const result = await Capacitor.Plugins.Clipboard?.read()
      if (result?.value) {
        setClipboardText(result.value)
        // Only populate clipboard when user hasn't prefilled input (e.g., from overlay)
        setInputText((prev) => prev?.trim().length ? prev : result.value)
        setState(prev => ({
          ...prev,
          currentInput: prev.currentInput?.trim().length ? prev.currentInput : result.value,
          clipboardHistory: [result.value, ...prev.clipboardHistory.slice(0, 4)]
        }))
      }
    } catch (error) {
      console.warn('Failed to read clipboard:', error)
    }
  }

  const handleCategorySelect = (categoryId: string) => {
    setSelectedCategory(categoryId)
    setState(prev => ({
      ...prev,
      selectedCategory: categoryId
    }))
  }

  const handleGenerate = async (prompt: string) => {
    if (!inputText.trim()) return

    setState(prev => ({ ...prev, isGenerating: true }))

    try {
      const finalPrompt = prompt.replace('{input}', inputText)
      
      // 触觉反馈
      if (isMobile) {
        await Capacitor.Plugins.Haptics?.impact({ style: 'medium' })
      }

      // 模拟AI生成
      await new Promise(resolve => setTimeout(resolve, 1000))
      const response = `AI生成回复: ${finalPrompt}`
      
      const newResponse = {
        id: Date.now().toString(),
        text: response,
        category: selectedCategory || '',
        timestamp: Date.now()
      }

      setState(prev => ({
        ...prev,
        generatedResponses: [newResponse, ...prev.generatedResponses],
        isGenerating: false
      }))

    } catch (error) {
      console.error('Generation failed:', error)
      setState(prev => ({ ...prev, isGenerating: false }))
    }
  }

  const handleCopyResult = async (text: string) => {
    try {
      await Capacitor.Plugins.Clipboard?.write({ string: text })
      
      if (isMobile) {
        await Capacitor.Plugins.Toast?.show({
          text: '已复制到剪贴板',
          duration: 'short'
        })
        await Capacitor.Plugins.Haptics?.impact({ style: 'light' })
      }
    } catch (error) {
      console.error('Failed to copy:', error)
    }
  }

  if (!state.isVisible) return null

  return (
    <div className="assistant-panel">
      <div className="panel-backdrop" onClick={onClose} />
      
      <div className="panel-content">
        <div className="panel-header">
          <h3>智能文本助手</h3>
          <button className="close-btn" onClick={onClose}>×</button>
        </div>

        <div className="input-section">
          <textarea
            value={inputText}
            onChange={(e) => {
              const val = e.target.value
              setInputText(val)
              setState(prev => ({ ...prev, currentInput: val }))
            }}
            placeholder="输入或粘贴文本..."
            className="text-input"
            rows={3}
          />
          
          <div className="input-actions">
            <button 
              className="paste-btn"
              onClick={loadClipboardContent}
              disabled={state.isGenerating}
            >
              📋 粘贴
            </button>
            
            <button 
              className="clear-btn"
              onClick={() => setInputText('')}
              disabled={state.isGenerating}
            >
              🗑️ 清空
            </button>
          </div>
        </div>

        <div className="preset-grid">
          {presetCategories.map((category) => (
            <div key={category.id} className="category-section">
              <button
                className={`category-btn ${selectedCategory === category.id ? 'active' : ''}`}
                onClick={() => handleCategorySelect(category.id)}
              >
                <span className="category-icon">{category.icon}</span>
                <span className="category-name">{category.name}</span>
              </button>
              
              {selectedCategory === category.id && (
                <div className="prompts-section">
                  {category.prompts.map((prompt, index) => (
                    <button
                      key={index}
                      className="prompt-btn"
                      onClick={() => handleGenerate(prompt)}
                      disabled={state.isGenerating || !inputText.trim()}
                    >
                      生成选项 {index + 1}
                    </button>
                  ))}
                </div>
              )}
            </div>
          ))}
        </div>

        {state.generatedResponses.length > 0 && (
          <div className="results-section">
            <h4>生成结果</h4>
            {state.generatedResponses.map((response) => (
              <div key={response.id} className="result-item">
                <div className="result-text">{response.text}</div>
                <button
                  className="copy-btn"
                  onClick={() => handleCopyResult(response.text)}
                >
                  📋 复制
                </button>
              </div>
            ))}
          </div>
        )}

        {state.isGenerating && (
          <div className="loading-section">
            <div className="loading-spinner">⏳</div>
            <span>AI正在生成中...</span>
          </div>
        )}
      </div>
    </div>
  )
}
